package com.totsp.lightningcalc;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.text.DecimalFormat;

/**
 * Quick demo Android application that estimates lightning distance
 * using "Flash to Bang" method.
 * 
 * 
 * @author ccollins
 *
 */
public class Main extends Activity {

   private static final int MENU_ABOUT = 1;
   private static final int MENU_PREFS = 2;
   private static final int MENU_NLSI = 3;

   private static final String EST_LIGHTNING_DIST = "Est. lightning distance:\n";
   private static final String MILE = "mile";
   private static final String MILES = "miles";
   private static final String KILOMETER = "km";
   private static final String KILOMETERS = "kms";
   private static final double MILES_DIVISOR = 5.0; // 5 seconds = 1 mile
   private static final double KILOMETERS_DIVISOR = 3.0; // 3 seconds = 1 click   
   //private static final int SOUND_SPEED_METERS_PER_SECOND = 350;

   // not thread safe, but we're only using one thread (UI thread)
   private static final DecimalFormat DEC_FORMAT = new DecimalFormat("###.0#");

   private ImageView lightning;
   private ImageView thunder;
   private TextView output;

   private SharedPreferences prefs;

   private boolean unitIsMiles;

   private boolean lightningClicked;
   private long start;
   private long finish;

   private Chronometer chrono;

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      prefs = PreferenceManager.getDefaultSharedPreferences(this);

      chrono = (Chronometer) findViewById(R.id.chronometer);

      lightning = (ImageView) findViewById(R.id.lightningicon);
      lightning.setOnClickListener(new OnClickListener() {
         public void onClick(View v) {
            if (lightningClicked) {
               Toast.makeText(Main.this, "Timer already started, click thunder to end.", Toast.LENGTH_LONG).show();
            } else {
               lightningClicked = true;
               start = SystemClock.elapsedRealtime();
               chrono.setBase(SystemClock.elapsedRealtime());
               chrono.start();
               output.setText("Click thunder to stop");
            }
         }
      });

      thunder = (ImageView) findViewById(R.id.thundericon);
      thunder.setOnClickListener(new OnClickListener() {
         public void onClick(View v) {
            if (lightningClicked) {
               lightningClicked = false;
               chrono.stop();
               finish = SystemClock.elapsedRealtime();
               long durationSeconds = (finish - start) / 1000;
               double distance = 0.0;
               String distanceString = null;
               if (unitIsMiles) {
                  distance = durationSeconds / MILES_DIVISOR;
                  distanceString = DEC_FORMAT.format(distance);
                  if (distance <= 1.0) {
                     output.setText(EST_LIGHTNING_DIST + distanceString + " " + MILE);
                  } else {
                     output.setText(EST_LIGHTNING_DIST + distanceString + " " + MILES);
                  }
               } else {
                  distance = durationSeconds / KILOMETERS_DIVISOR;
                  distanceString = DEC_FORMAT.format(distance);
                  if (distance <= 1.0) {
                     output.setText(EST_LIGHTNING_DIST + distanceString + " " + KILOMETER);
                  } else {
                     output.setText(EST_LIGHTNING_DIST + distanceString + " " + KILOMETERS);
                  }
               }
            } else {
               Toast.makeText(Main.this, "Timer not yet started, click lightning to begin.", Toast.LENGTH_LONG).show();
            }
         }
      });

      output = (TextView) findViewById(R.id.output);
      output.setText("Click lightning to start");
   }

   @Override
   protected void onStart() {
      super.onStart();
      String unitType = prefs.getString("distanceunit", "m");
      if (unitType.equals("m")) {
         unitIsMiles = true;
      } else {
         unitIsMiles = false;
      }
   }

   @Override
   protected void onPause() {
      lightningClicked = false;
      chrono.stop();
      super.onPause();
   }

   @Override
   public boolean onCreateOptionsMenu(final Menu menu) {
      menu.add(0, Main.MENU_ABOUT, 1, "About").setIcon(android.R.drawable.ic_menu_help);
      menu.add(0, Main.MENU_PREFS, 2, "Prefs").setIcon(android.R.drawable.ic_menu_preferences);
      menu.add(0, Main.MENU_NLSI, 3, "Safety").setIcon(android.R.drawable.ic_menu_info_details);
      return super.onCreateOptionsMenu(menu);
   }

   @Override
   public boolean onOptionsItemSelected(final MenuItem item) {
      switch (item.getItemId()) {
         case MENU_ABOUT:
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("file:///android_asset/release_notes.html"),
                     Main.this, HTMLScreen.class));
            return true;
         case MENU_PREFS:
            startActivity(new Intent(Main.this, Preferences.class));
            return true;
         case MENU_NLSI:
            Uri uri = Uri.parse("http://www.lightningsafety.com/");
            startActivity(new Intent(Intent.ACTION_VIEW, uri));
            return true;
         default:
            return super.onOptionsItemSelected(item);
      }
   }
}